package cn.yunbamboos.application;

import cn.yunbamboos.utils.NetworkUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.Environment;

import java.util.ArrayList;
import java.util.List;

public class Application {

    private static final Logger logger = LoggerFactory.getLogger(Application.class);

    private final List<Class<?>> primarySourceList = new ArrayList<>();

    private String[] args;

    /**
     * 创建应用程序
     * */
    public static Application create(){
        return new Application();
    }

    /**
     * 添加启动主要来源类
     * */
    public Application addPrimarySource(Class<?> primarySource) {
        this.primarySourceList.add(primarySource);
        return this;
    }

    /**
     * 启动参数
     * */
    public Application setArgs(String[] args) {
        this.args = args;
        return this;
    }

    /**
     * 运行应用程序
     * */
    public ConfigurableApplicationContext run() {
        primarySourceList.add(Application.class);
        Class<?>[] primarySources = primarySourceList.toArray(new Class<?>[0]);
        SpringApplication application = new SpringApplication(primarySources);
        ConfigurableApplicationContext context = application.run(args);
        Environment environment = context.getEnvironment();
        String port = environment.getProperty("server.port", "80");
        String contextPath = environment.getProperty("server.servlet.context-path", "");
        String projectPath = environment.getProperty("rest-service.project-path", "");
        String restServicePath = environment.getProperty("rest-service.rest-service-path", "");
        logger.info("server port {}", port);

        List<String> ips = NetworkUtils.getIPS();
        for (String ip : ips) {
            logger.info("REST服务访问地址: http://{}:{}{}{}{}", ip, port, contextPath, projectPath, restServicePath);
        }
        logger.info("");
        for (String ip : ips) {
            logger.info("WEB服务访问地址: http://{}:{}{}", ip, port, contextPath);
        }
        return context;
    }


}
